package controllers

import (
	"baokaobang/conf"
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"fmt"
	"github.com/kataras/iris/v12"
	"strings"
)

type University struct {
	Ctx iris.Context
}

// 获取首页广告的大学
func (c *University) PostShowhome() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	universityList := make([]models.UniversityData, 0)
	err = db.Table("university").Where("is_show_index = 1").Find(&universityList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取首页广告大学：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功获取首页广告大学列表", universityList)
}

// 获取数据查询页广告的大学
func (c *University) PostShowsearch() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	universityList := make([]models.UniversityData, 0)
	err = db.Table("university").Where("is_show_data = 1").Find(&universityList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取数据查询页广告大学：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功获取数据查询页广告大学列表", universityList)
}

// 获取热门大学
func (c *University) PostHot() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	universityList := make([]models.UniversityRegion, 0)
	err = db.Table("university").Alias("u").
		Join("INNER", []string{"region", "p"}, "u.province_id = p.id").
		Join("INNER", []string{"region", "c"}, "u.city_id = c.id").
		Where("u.is_hot = 1").Limit(8).Find(&universityList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取热门大学：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功获取热门大学列表", universityList)
}

// 获取大学列表
func (c *University) PostList() interface{} {
	curPage := utils.Atoi(c.Ctx.PostValueDefault("curPage", "1"))
	keywords := strings.TrimSpace(c.Ctx.PostValueDefault("keywords", ""))
	start := (curPage - 1) * conf.ListDataConfig.PerPage

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	universityList := make([]models.UniversityData, 0)
	sess := db.Table(new(models.University)).Limit(conf.ListDataConfig.PerPage, start)
	if len(keywords) > 0 {
		sess = sess.Where("`name` like ?", fmt.Sprintf("%%%s%%", keywords))
	}
	err = sess.Find(&universityList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取大学列表：%s", err.Error()), "")
	}

	for i, university := range universityList {
		universityLabelList := make([]models.UniversityLabelObj, 0)
		db.Table("university_label").Alias("ul").
			Join("INNER", []string{"label", "l"}, "ul.label_id = l.id").
			Where("ul.university_id = ?", university.Id).Limit(3).Find(&universityLabelList)
		universityList[i].LabelList = universityLabelList
	}

	return utils.CommonRes(20000, "成功获取大学列表", universityList)
}

